const bcrypt = require('bcrypt');
const randomsstring = require('randomstring');
const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken');




//新增hash密码
exports.hash = (myPlaintextPassword) => {
  return new Promise((resolve, reject) => {
    bcrypt.genSalt(10, function (err, salt) {
      bcrypt.hash(myPlaintextPassword, salt, function (err, hash) {
        if (err) {
          reject(err);
        }
        resolve(hash);
      })
    })
  })
}

//校验用户账号和密码
exports.compare = (myPlaintextPassword, hash) => {
  return new Promise((resolve, reject) => {
    bcrypt.compare(myPlaintextPassword, hash, function (err, result) {
      resolve(result);
    })
  })
}

//获取sessionId 设置sessionId存入Cookie
exports.setCookie = (res) => {
  const sessionId = randomsstring.generate();
  res.set('Set-Cookie', `sessionId=${sessionId}; Path=/; HttpOnly`);
}

exports.sign = (username) => {
  const privateKey = fs.readFileSync(path.join(__dirname, '../keys/rsa_private_key.pem'));

  //生成token
  const token = jwt.sign({
    username
  }, privateKey, {
    algorithm: 'RS256'
  });
  return token;
}

exports.verify = (token) => {
  const publicKey = fs.readFileSync(path.join(__dirname, '../keys/rsa_public_key.pem'));
  const result = jwt.verify(token, publicKey);
  return result;
}